package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-27
 * Time: 9:38
 */
public class MessageDao {

    // 往数据库中存放留言
    public void save(Message message) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "insert into message value(?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.getMessage());
            int row = statement.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }

    public List<Message> load() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        List<Message> messageList = new ArrayList<>();
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while(resultSet.next()) {
                Message message = new Message();
                message.setMessage(resultSet.getString("message"));
                messageList.add(message);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return messageList;
    }
}
